package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"proj-man-edu/cache"
	"proj-man-edu/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {

	title := c.PostForm("title")
	content := c.PostForm("content")
	userID, _ := strconv.Atoi(c.PostForm("user_id"))
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := model.Video{

		Title:   title,
		Content: content,
		UserID:  userID,
	}

	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	redis_key := "video_id_" + strconv.Itoa(int(data.ID))
	var video model.Video
	model.DB.Where("id = ?", video.ID).First(&video)
	jsonData, _ := json.Marshal(video)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func List(c *gin.Context) {
	var video []model.Video

	redis_key := "video_list_"
	cacheDate, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheDate == "" {
		model.DB.Find(&video)
		jsonDate, _ := json.Marshal(video)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonDate, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheDate), &video)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": video,
	})

}

func Del(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	model.DB.Where("id = ?", id).Delete(&model.Video{}).Debug()

	redis_key := "video_del_" + strconv.Itoa(id)
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var video model.Video
	err := model.DB.Where("id = ?", id).First(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查找失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查找成功",
		"data": video,
	})
	return
}
